package co.com.ejb.security.test;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.junit.Assert;
import org.junit.Test;

import co.com.ejb.security.SecureSchoolLocalBusiness;
import co.com.ejb.security.fireDepartment.FireDepartmentLocalBusiness;

public class SecurityTestSuite {

	/**
	 * Ensures that any unauthenticated user can declare an emergency,
	 * hence closing the school
	 */
	@Test
	public void anyoneCanDeclareEmergencyAndCloseSchool() throws NamingException
	{
		/**
		 * http://biemond.blogspot.com/2009/12/ejb-session-bean-security-in-weblogic.html
		 */
		
		Properties parm = new Properties();  
        parm.setProperty("java.naming.factory.initial","weblogic.jndi.WLInitialContextFactory");  
        parm.setProperty("java.naming.provider.url","t3://localhost:7101");  
        parm.setProperty("java.naming.security.principal","eliel");  
        parm.setProperty("java.naming.security.credentials","weblogic1");  
        final Context context =  new InitialContext(parm); 
        
		// Assume we have a couple EJB proxies with unauthenticated caller
		final SecureSchoolLocalBusiness school = null; // From somewhere
		final FireDepartmentLocalBusiness fireDepartment = null; // From somewhere
		// First check that school's open
		Assert.assertTrue("School should be open to start the test", school.isOpen());
		// Ensure we can't close the school directly (we don't have access)
		boolean gotAccessException = false;
		try
		{
			school.close();
		}
		catch (final EJBAccessException e)
		{
			// Expected
			System.out.println("We can't close the school on our own, make an emergency");
			gotAccessException = true;
		}
		Assert.assertTrue("We shouldn't be able to close school directly",
				gotAccessException);
		// Now declare an emergency via the fire department
		fireDepartment.declareEmergency();
		// The school should now be closed, even though we
		// don't have rights to do that directly on our own.
		Assert.assertFalse("School should be closed after emergency was declared",
				school.isOpen());
	}
}


